﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace I_Organization.Infrastructure
{
    /// <summary>
    /// 仓储实现类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaceRepository<T> : IRepository<T> where T : class, new()
    {
        EFDbContext db;

        public IQueryable<T> All { get; }

        public async Task<int> AddAsync(T model)
        {
            await db.AddAsync(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> AddCountAsync(List<T> model)
        {
            await db.AddRangeAsync(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(int id)
        {
            var ids = await db.Set<T>().FindAsync(id);
            db.Set<T>().Remove(ids);
            return await db.SaveChangesAsync();
        }

        public async Task<int> DeleteAsync(T info)
        {
            db.Set<T>().Update(info);
            return await db.SaveChangesAsync();
        }

        public Task<IQueryable<T>> GetAll()
        {
            IQueryable<T> item = db.Set<T>();
            return Task.FromResult(item);
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }

        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await db.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }

        public async Task<int> DelCount(Expression<Func<T, bool>> expression)
        {
            var ids = db.Set<T>().Where(expression).ToArray();
            db.RemoveRange(ids);
            return await db.SaveChangesAsync();
        }

        public async Task<int> LoDelete(T info)
        {
            db.Remove(info);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateAsync(T model)
        {
            db.Update(model);
            return await db.SaveChangesAsync();
        }

        public async Task<int> UpdateUpdAsync(List<T> list)
        {
            db.UpdateRange(list);
            return await db.SaveChangesAsync();
        }

        public async Task<T> GetAsyncs(Expression<Func<T, bool>> expre)
        {
            //DbSet<T> dbset = db.Set<T>();
            //return await dbset.FirstOrDefaultAsync(expre);
            return await db.Set<T>().Where(expre).FirstOrDefaultAsync();
        }

        public async Task<T> GetModelAsync(Expression<Func<T, bool>> expre)
        {
            return await db.Set<T>().FirstOrDefaultAsync(expre);
        }
    }
}
